<?php
/*********************************************
<!-- 
*   	DOTA OPENSTATS
*   
*	Developers: Ivan.
*	Contact: ivan.anta@gmail.com - Ivan
*
*	
*	Please see http://openstats.iz.rs
*	and post your webpage there, so I know who's using it.
*
*	Files downloaded from http://openstats.iz.rs
*
*	Copyright (C) 2010  Ivan
*
*
*	This file is part of DOTA OPENSTATS.
*
* 
*	 DOTA OPENSTATS is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    DOTA OPEN STATS is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with DOTA OPEN STATS.  If not, see <http://www.gnu.org/licenses/>
*
-->
**********************************************/
if (!isset($website) ) {header('HTTP/1.1 404 Not Found'); die; }

$errors = "";

include("Hook.php");
include("default-constants.php");

date_default_timezone_set($TimeZone);

function add_event($event, $value = NULL, $callback = NULL)
{
    static $events;

    // Adding or removing a callback?
    if($callback !== NULL)
    {
        if($callback)
        {
            $events[$event][] = $callback;
        }
        else
        {
            unset($events[$event]);
        }
    }
    elseif(isset($events[$event])) // Fire a callback
    {
        foreach($events[$event] as $function)
        {
            $value = call_user_func($function, $value);
        }
        return $value;
    }
}

	
  function safeEscape($text)
  {
   if (is_numeric($text)) $text=floor($text);
  $text = htmlspecialchars(strip_tags($text));
  $text = mysql_real_escape_string($text);
  $text = str_replace ('"','',$text);
  $text = str_replace(array("%20", "\"", "'", "\\", "=", ";", ":"), array("","","","","","",""), $text);
  return $text;
  }
  
  
  function EscapeStr($text)
  {
  $text = mysql_real_escape_string($text);
  //$text = str_replace(array("%20", "\"", "'", "\\", "=", ";", ":"), "", $text);
  return $text;
  }
  
function FilterData($data) {
    $data = trim(htmlentities(strip_tags($data)));
 
    if (get_magic_quotes_gpc())
        $data = stripslashes($data);
 
    $data = mysql_real_escape_string($data);
 
    return $data;
}

function ShowUserAvatar( $avatar, $w = "64", $h = "64", $style="", $RemoveAvatar = "Remove Avatar", $Default = 0 ) {
  
    if ($w>=8 AND $h>=8) { $dim =' width="'.$w.'" height="'.$h.'"'; } else $dim = "";
	if ( !empty($style) ) $_style=' style="'.$style.'"'; else $_style = "";

  if ( !empty($avatar) ) {
  ?>
  <img src="<?=$avatar?>" <?=$dim?> alt="avatar" <?=$_style?> class="imgvaligntop user_avatar" />
  <?php if ($RemoveAvatar!="") { ?>
  <input type="checkbox" name="removeAvatar" value="1" /> <?=$RemoveAvatar?>
  <?php } ?>
  <?php
  } else {
    if ( $Default == 1) {
	?><img src="img/avatar_64.png" <?=$dim?> alt="avatar" <?=$_style?> class="imgvaligntop user_avatar" /><?php
	}
  }
}

function UploadAvatar ( $allowed = "0", $CurrentAvatar = "", $UploadTitle = "Upload Image" ) {
  if ( $allowed == 1 AND empty($CurrentAvatar) ) {
  ?>
  <input name="avatar_upload" id="new_image" size="30" type="file" class="fileUpload" /> 
  <?php /* <button name="submit_avatar" type="submit" class="menuButtons"><?=$UploadTitle?></button><?php */ ?>
  <?php
  }
}

function OS_is_admin() {
  if (is_logged() AND isset($_SESSION["level"] ) AND $_SESSION["level"]>=9 ) {
  return true;
  } else return false;
}

function OS_PluginEdit() {
  if ( isset($_GET["plugins"]) AND isset($_GET["edit"]) ) return true;
  else 
      return false;
}

function EditUserLink($id) {
 ?>
 <a href="adm/?users&amp;edit=<?=$id?>">edit</a>
 <?php
}

function UserGender( $gender, $male = "Male", $female = "female" ) {
   if ( $gender == 1 ) return $male;
   if ( $gender == 2 ) return $female;
}
  
  function secondsToTime($seconds, $h = ":", $m = ":", $s = "")//Returns the time like 1:43:32
{
	$hours = floor($seconds/3600);
	$secondsRemaining = $seconds % 3600;
	
	$minutes = floor($secondsRemaining/60);
	$seconds_left = $secondsRemaining % 60;
	
	if($hours != 0)
	{
		if(strlen($minutes) == 1)
		{
		$minutes = "0".$minutes;
		}
		if(strlen($seconds_left) == 1)
		{
		$seconds_left = "0".$seconds_left;
		}
		return $hours."$h".$minutes."$m".$seconds_left."$s";
	}
	else
	{
		if(strlen($seconds_left) == 1)
		{
		$seconds_left = "0".$seconds_left;
		}
		return $minutes."$m".$seconds_left."";
	}
}

   function millisecondsToTime($milliseconds)//returns the time like 5.2 (5 seconds, 200 milliseconds)
{
	$return="";
	$return2="";
     // get the seconds
	$seconds = floor($milliseconds / 1000) ;
	$milliseconds = $milliseconds % 1000;
	$milliseconds = round($milliseconds/100,0);
	
	// get the minutes
	$minutes = floor($seconds / 60) ;
	$seconds_left = $seconds % 60 ;

	// get the hours
	$hours = floor($minutes / 60) ;
	$minutes_left = $minutes % 60 ;
// A little unneccasary with minutes and hours,,  but HEY  everythings possible
	if($hours)
	{
		$return ="$hours"."h ";
	}
	if($minutes_left)
	{
		$return2 ="$minutes_left"."m ";
	}
return $return.$return2.$seconds_left.".".$milliseconds;
}  

///////////////////////////////////////////////////////////////
     function replayDuration($seconds)
{
	$minutes = floor($seconds/60);
	$seconds_left = $seconds % 60;
	
	if(strlen($seconds_left) == 1)
	{
	$seconds_left = "0".$seconds_left;
	}
	return $minutes."m".$seconds_left."s";
}

   
    function getTeam($color)
{
	switch ($color) {
		case 'red': return 0;
		case 'blue': return 1;
		case 'teal': return 1;
		case 'purple': return 1;
		case 'yellow': return 1;
		case 'orange': return 1;
		case 'green': return 0;
		case 'pink': return 2;
		case 'gray': return 2;
		case 'light-blue': return 2;
		case 'dark-green': return 2;
		case 'brown': return 2;
		case 'observer': return 0;
	}
}

    function getSingleGame($gameid) {
	 $sql = "SELECT winner, creatorname, duration, datetime, gamename, stats, views
     FROM ".OSDB_DG." AS dg 
     LEFT JOIN ".OSDB_GAMES." AS d ON d.id = dg.gameid 
     WHERE dg.gameid='".(int)$gameid."'";
	 
	 return $sql;
	}
      ///////////////
     // GAME INFO //
    ///////////////
	function getUserGames ($id, $MinDuration, $offset, $rowsperpage, $filter = "" ) {
	
	 $sql = "SELECT s.*, g.id, g.map, g.gamename, g.datetime, g.ownername, g.duration,  g.creatorname, dg.winner, 
	 g.gamestate AS type, s.player, dp.kills, dp.deaths, dp.creepkills, dp.creepdenies, dp.assists, dp.hero, dp.neutralkills, dp.newcolour
	 FROM ".OSDB_STATS." as s 
	 LEFT JOIN ".OSDB_GP." as gp ON LOWER(gp.name) = LOWER(s.player)
	 LEFT JOIN ".OSDB_GAMES." as g ON g.id = gp.gameid
	 LEFT JOIN ".OSDB_DG." as dg ON g.id = dg.gameid 
	 LEFT JOIN ".OSDB_DP." as dp ON dp.gameid = dg.gameid AND gp.colour = dp.colour
	 WHERE s.id = '".$id."' AND LOWER(g.map) LIKE ('%dota%') AND g.duration>='".$MinDuration."' ".$filter."
	 LIMIT $offset, $rowsperpage";
	 
	return $sql;
	}
	
	
	function getAllGames($MinDuration, $offset, $rowsperpage, $filter="", $order = "id DESC" ) {
	  $sql = "SELECT 
          g.id, g.views, g.stats, g.map, g.datetime, g.gamename, g.ownername, g.duration, g.creatorname, dg.winner, 
		  g.gamestate  type, g.creatorserver as server
		  FROM ".OSDB_GAMES." as g 
		  LEFT JOIN ".OSDB_DG." as dg ON g.id = dg.gameid 
		  
		  WHERE LOWER(map) LIKE '%dota%' AND duration>='".$MinDuration."' $filter
		  ORDER BY $order
		  LIMIT $offset, $rowsperpage";
	return $sql;
	// LEFT JOIN ".OSDB_DP." as dp ON dp.gameid = g.id
	}
	
	
    function getGameInfo($gid){
	$sql = "
	   SELECT winner, dp.gameid, gp.colour, newcolour, original as hero, description, dp.kills, dp.deaths, dp.assists, dp.creepkills, dp.creepdenies, dp.neutralkills, dp.towerkills, dp.gold,  dp.raxkills, dp.courierkills, s.id as userid,
	   item1, item2, item3, item4, item5, item6, spoofedrealm,
	   it1.icon as itemicon1, 
	   it2.icon as itemicon2, 
	   it3.icon as itemicon3, 
	   it4.icon as itemicon4, 
	   it5.icon as itemicon5, 
	   it6.icon as itemicon6, 
	   it1.name as itemname1, 
	   it2.name as itemname2, 
	   it3.name as itemname3, 
	   it4.name as itemname4, 
	   it5.name as itemname5, 
	   it6.name as itemname6, 
	   leftreason, 
	   gp.left, 
	   gp.name as name, 
	   gp.ip as ip,
	   b.name as banname 
	   FROM ".OSDB_DP." AS dp 
	   LEFT JOIN ".OSDB_GP." AS gp ON gp.gameid = dp.gameid and dp.colour = gp.colour 
	   LEFT JOIN ".OSDB_DG." AS dg ON dg.gameid = dp.gameid 
	   LEFT JOIN ".OSDB_GAMES." AS g ON g.id = dp.gameid 
	   LEFT JOIN ".OSDB_BANS." as b ON b.name=gp.name
	   LEFT JOIN ".OSDB_HEROES." as f ON hero = heroid
	   LEFT JOIN ".OSDB_ITEMS." as it1 ON it1.itemid = item1
	   LEFT JOIN ".OSDB_ITEMS." as it2 ON it2.itemid = item2
	   LEFT JOIN ".OSDB_ITEMS." as it3 ON it3.itemid = item3
	   LEFT JOIN ".OSDB_ITEMS." as it4 ON it4.itemid = item4
	   LEFT JOIN ".OSDB_ITEMS." as it5 ON it5.itemid = item5
	   LEFT JOIN ".OSDB_ITEMS." as it6 ON it6.itemid = item6
	   LEFT JOIN ".OSDB_STATS." as s ON LOWER(s.player) = LOWER(gp.name)
	   WHERE dp.gameid='".(int)$gid."'
	   GROUP by gp.name
	   ORDER BY newcolour";
	   return $sql;
	}

	function getSentScourWon(){
	$sql = "SELECT COUNT(*) as total, 
          SUM(case when(dg.winner = 1) then 1 else 0 end) as sentinelWon,
		  SUM(case when(dg.winner = 2) then 1 else 0 end) as scourgeWon,
		  SUM(case when(dg.winner = 0) then 1 else 0 end) as draw 
		  FROM ".OSDB_DG." as dg 
		  WHERE dg.winner = 1 OR dg.winner = 2 OR dg.winner = 0
		  LIMIT 1";
		  
		  return $sql;
	}
	
	function getGamesSummary($who){
	$sql = "SELECT 
	SUM(kills) as Kills,
	SUM(deaths) as Deaths,
	SUM(creepkills) as CreepKills,
	SUM(creepdenies) as CreepDenies,
	SUM(towerkills) as towerkills,
	SUM(raxkills) as raxkills,
	SUM(courierkills) as courierkills,
	SUM(assists) as Assists
	FROM ".OSDB_DP." as dp 
	LEFT JOIN ".OSDB_DG." as dg ON dg.gameid = dp.gameid
	WHERE dg.winner = '".(int)$who."' AND  dg.winner != 0 LIMIT 1";
		  
		  return $sql;
	}
	
	  /////////////////////////////////////////////////////////////////
	 //                          ITEMS                              //
	/////////////////////////////////////////////////////////////////
	function getMostUsedHeroByItem($heroid, $itemid, $tot, $itemName ) {

	//FIND AND CHECK ALL GROUPED ITEMS 
       if (
	       !strstr($itemName,"Aghanim") 
	   AND !strstr($itemName,"Armlet of Mordiggian") 
	   AND !strstr($itemName,"Black King Bar") 
	   AND !strstr($itemName,"Dagon Lev")
	   AND !strstr($itemName,"Diffusal Blade")
	   AND !strstr($itemName,"Divine Rapier")
	   AND !strstr($itemName,"Bottle")
	   AND !strstr($itemName,"Linken")
	   AND !strstr($itemName,"Power Treads")
	   AND !strstr($itemName,"Monkey King Bar")
	   AND !strstr($itemName,"Eye of Skadi")
	   AND !strstr($itemName,"Orb of Venom")
	   AND !strstr($itemName,"Necronomicon Lev")
	   AND !strstr($itemName,"Urn of Shadows")
	   AND !strstr($itemName,"Dust of Appearance")
	   AND !strstr($itemName,"s Dagger")
	   AND !strstr($itemName,"Heart of Tarrasque")
	   AND !strstr($itemName,"Radiance")
	   )
	{
	$sql = "SELECT COUNT(*) as total, dp.item1,dp.item2, dp.item3, dp.item4, dp.item5, dp.item6, 
	dp.hero, h.heroid, h.description as heroname 
	FROM ".OSDB_DP." as dp 
	LEFT JOIN ".OSDB_HEROES." as h ON h.original = dp.hero AND h.summary != '-'
	WHERE dp.hero = '$heroid' AND dp.hero !=''
	OR dp.item1 = '$itemid' 
	OR dp.item2 = '$itemid'  
	OR dp.item3 = '$itemid'
	OR dp.item4 = '$itemid'
	OR dp.item5 = '$itemid'
	OR dp.item6 = '$itemid' 
	GROUP BY dp.hero 
	ORDER BY count(*) DESC LIMIT $tot";}
	else {
	if (strstr($itemName,"Aghanim"))           $itemName = "Aghanim";
	if (strstr($itemName,"Black King Bar"))    $itemName = "Black King Bar";
	if (strstr($itemName,"Dagon"))             $itemName = "Dagon";
	if (strstr($itemName,"Diffusal Blade"))    $itemName = "Diffusal Blade";
	if (strstr($itemName,"Divine Rapier"))     $itemName = "Divine Rapier";
	if (strstr($itemName,"Bottle"))            $itemName = "Bottle";
	if (strstr($itemName,"Linken"))            $itemName = "Linken";
	if (strstr($itemName,"Power Treads"))      $itemName = "Power Treads";
	if (strstr($itemName,"Monkey King Bar"))   $itemName = "Monkey King Bar";
	if (strstr($itemName,"Eye of Skadi"))      $itemName = "Eye of Skadi";
	if (strstr($itemName,"Orb of Venom"))      $itemName = "Orb of Venom";
	if (strstr($itemName,"Necronomicon Lev"))  $itemName = "Necronomicon Lev";
	if (strstr($itemName,"Urn of Shadows"))    $itemName = "Urn of Shadows";
	if (strstr($itemName,"Dust of Appearance"))   $itemName = "Dust of Appearance";
	if (strstr($itemName,"s Dagger"))             $itemName = "s Dagger";
	if (strstr($itemName,"Armlet of Mordiggian")) $itemName = "Armlet of Mordiggian";
	if (strstr($itemName,"Heart of Tarrasque"))   $itemName = "Heart of Tarrasque";
	if (strstr($itemName,"Radiance"))          $itemName = "Radiance";
	
	$sql = "SELECT COUNT(*) as total, dp.item1,dp.item2, dp.item3, dp.item4, dp.item5, dp.item6, dp.hero, h.heroid, h.description as heroname, it.name, it.itemid
	FROM ".OSDB_DP." as dp 
	LEFT JOIN ".OSDB_HEROES." as h ON h.original = dp.hero AND h.summary != '-'
	LEFT JOIN ".OSDB_ITEMS." as it  ON it.name  LIKE ('%$itemName%') AND  it.item_info!=''  AND (it.itemid = dp.item1)  
	LEFT JOIN ".OSDB_ITEMS." as it2 ON it2.name LIKE ('%$itemName%') AND  it2.item_info!='' AND (it2.itemid = dp.item2) 
	LEFT JOIN ".OSDB_ITEMS." as it3 ON it3.name LIKE ('%$itemName%') AND  it3.item_info!='' AND (it3.itemid = dp.item3) 
	LEFT JOIN ".OSDB_ITEMS." as it4 ON it4.name LIKE ('%$itemName%') AND  it4.item_info!='' AND (it4.itemid = dp.item4) 
	LEFT JOIN ".OSDB_ITEMS." as it5 ON it5.name LIKE ('%$itemName%') AND  it5.item_info!='' AND (it5.itemid = dp.item5) 
	LEFT JOIN ".OSDB_ITEMS." as it6 ON it6.name LIKE ('%$itemName%') AND  it6.item_info!='' AND (it6.itemid = dp.item6) 
	WHERE dp.hero = '$heroid' AND dp.hero !='' 
    OR it.name LIKE ('%$itemName%') OR it2.name LIKE ('%$itemName%') OR it3.name LIKE ('%$itemName%') 
	OR it4.name LIKE ('%$itemName%') OR it5.name LIKE ('%$itemName%') OR it6.name LIKE ('%$itemName%')
	GROUP BY dp.hero 
	ORDER BY count(*) DESC,  dp.hero DESC LIMIT $tot";
	  }
	
	  return $sql;
	}

    function getMonthName($month,
	$ljan = "JAN",
	$lfeb = "FEB",
	$lmar = "MAR",
	$lapr = "APR",
	$lmay = "MAY",
	$ljun = "JUN",
	$ljul = "JUL",
	$laug = "AUG",
	$lsep = "SEP",
	$loct = "OCT",
	$lnov = "NOV",
	$ldec = "DEC"
	           ) 
	{
	if ($month == 1) $rmonth = $ljan;
	if ($month == 2) $rmonth = $lfeb;
	if ($month == 3) $rmonth = $lmar;
	if ($month == 4) $rmonth = $lapr;
	if ($month == 5) $rmonth = $lmay;
	if ($month == 6) $rmonth = $ljun;
	if ($month == 7) $rmonth = $ljul;
	if ($month == 8) $rmonth = $laug;
	if ($month == 9) $rmonth = $lsep;
	if ($month == 10) $rmonth = $loct;
	if ($month == 11) $rmonth = $lnov;
	if ($month == 12) $rmonth = $ldec;
	
	return $rmonth;
	
	}
	
	function getDays($m){
	return 31;
	if ($m == 1) return 31;
	if ($m == 2) return 28;
	if ($m == 3) return 31;
	if ($m == 4) return 30;
	if ($m == 5) return 31;
	if ($m == 6) return 30;
	if ($m == 7) return 31;
	if ($m == 8) return 30;
	if ($m == 9) return 31;
	if ($m == 10) return 30;
	if ($m == 11) return 31;
	if ($m == 12) return 30;
	}

   
///////////////////////
    function getHero($heroid) {
	$text = "SELECT * FROM ".OSDB_HEROES." WHERE original='$heroid' AND summary!= '-' LIMIT 1";
	return $text;
	}

    function getHeroInfo($heroid, $minPlayedRatio, $minPlayedRatio) {
	$text = "SELECT *, 
	(kills*1.0/deaths) as kdratio, 
	(wins*1.0/losses) as winratio, 
	summary, 
	skills, 
	stats 
	FROM 
	(SELECT count(*) as totgames, 
	original,
	SUM(case when(((dg.winner = 1 and dp.newcolour < 6) 
	or (dg.winner = 2 and dp.newcolour > 6)) 
	AND gp.`left`/g.duration >= $minPlayedRatio) then 1 else 0 end) as wins, 
	SUM(case when(((dg.winner = 2 and dp.newcolour < 6) 
	or (dg.winner = 1 and dp.newcolour > 6)) 
	AND gp.`left`/g.duration >= $minPlayedRatio) then 1 else 0 end) as losses, 
	SUM(kills) as kills, 
	SUM(deaths) as deaths, 
	SUM(assists) as assists, 
	SUM(creepkills) as creepkills, 
	SUM(creepdenies) as creepdenies, 
	SUM(neutralkills) as neutralkills, 
	SUM(towerkills) as towerkills, 
	SUM(raxkills) as raxkills, 
	SUM(courierkills) as courierkills
	FROM ".OSDB_DP." AS dp 
	LEFT JOIN ".OSDB_HEROES." as b ON hero = heroid 
	LEFT JOIN ".OSDB_DG." as dg ON dg.gameid = dp.gameid
	LEFT JOIN ".OSDB_GP." as gp ON gp.gameid = dp.gameid and dp.colour = gp.colour 
	LEFT JOIN ".OSDB_GAMES." as g ON gp.gameid = g.id 
	WHERE original='$heroid' 
	GROUP BY original) as y 
	LEFT JOIN ".OSDB_HEROES." as h ON y.original = h.heroid LIMIT 1";
	
	return $text;
	}
	
	function getHeroHistoryCount($heroid) {
	$text = "
	SELECT COUNT(*) AS  count 
	 FROM (
	       SELECT name 
	       FROM ".OSDB_DP." AS dp 
	       LEFT JOIN ".OSDB_GP." AS gp ON gp.gameid = dp.gameid and dp.colour = gp.colour 
	       LEFT JOIN ".OSDB_DG." AS dg ON dg.gameid = dp.gameid 
	       LEFT JOIN ".OSDB_GAMES." AS g ON g.id = dp.gameid 
	       LEFT JOIN ".OSDB_HEROES." as e ON dp.hero = heroid 
	       WHERE heroid = '$heroid')as t LIMIT 1";
 
	return $text;
	}
	
	//HERO MOST USED ITEMS
	function getHeroItem1($heroid) {
	$sql = "SELECT count(*) as total, dp.item1, i.icon , i.name , i.itemid 
	FROM ".OSDB_DP." as dp
	LEFT JOIN ".OSDB_ITEMS." as i ON i.itemid = dp.item1
	WHERE hero = '$heroid' 
	AND dp.item1 != '\0\0\0\0' 
    AND dp.item1 != '' 
	GROUP BY item1 having count(*) > 1 
	ORDER BY count(*) DESC LIMIT 2";
	return $sql;
	}
	function getHeroItem2($heroid,$mostItem1,$mostItem11) {
	$sql = "SELECT count(*) as total, dp.item2, i.icon , i.name , i.itemid
	FROM ".OSDB_DP." as dp
	LEFT JOIN ".OSDB_ITEMS." as i ON i.itemid = dp.item2
	WHERE hero = '$heroid' 
	AND dp.item2 != '\0\0\0\0' 
    AND dp.item2 != '' 
	AND dp.item2 != '$mostItem1' AND dp.item2 != '$mostItem11'
	GROUP BY item2 having count(*) > 1 
	ORDER BY count(*) DESC LIMIT 2";
	return $sql;
	}
	function getHeroItem3($heroid,$mostItem1,$mostItem11,$mostItem2,$mostItem22) {
	$sql = "SELECT count(*) as total, dp.item3, i.icon , i.name , i.itemid
	FROM ".OSDB_DP." as dp 
	LEFT JOIN ".OSDB_ITEMS." as i ON i.itemid = dp.item3
	WHERE hero = '$heroid' 
	AND dp.item3 != '\0\0\0\0' 
    AND dp.item3 != '' 
	AND dp.item3 != '$mostItem1' AND dp.item3 != '$mostItem11'
	AND dp.item3 != '$mostItem2' AND dp.item3 != '$mostItem22'
	GROUP BY item3 having count(*) > 1 
	ORDER BY count(*) DESC LIMIT 2";
	return $sql;
	}
	function getHeroItem4($heroid,$mostItem1,$mostItem11,$mostItem2,$mostItem22,$mostItem3,$mostItem33) {
	$sql = "SELECT count(*) as total, dp.item4, i.icon , i.name , i.itemid
	FROM ".OSDB_DP." as dp
	LEFT JOIN ".OSDB_ITEMS." as i ON i.itemid = dp.item4
	WHERE hero = '$heroid' 
	AND dp.item4 != '\0\0\0\0' 
    AND dp.item4 != '' 
	AND dp.item4 != '$mostItem1' AND dp.item4 != '$mostItem11'
	AND dp.item4 != '$mostItem2' AND dp.item4 != '$mostItem22'
	AND dp.item4 != '$mostItem3' AND dp.item4 != '$mostItem33'
	GROUP BY item4 having count(*) > 1 
	ORDER BY count(*) DESC LIMIT 2";
	return $sql;
	}
	function getHeroItem5($heroid,$mostItem1,$mostItem11,$mostItem2,$mostItem22,$mostItem3,$mostItem33,$mostItem4,$mostItem44) {
	$sql = "SELECT count(*) as total, dp.item5, i.icon , i.name , i.itemid
	FROM ".OSDB_DP." as dp
	LEFT JOIN ".OSDB_ITEMS." as i ON i.itemid = dp.item5
	WHERE hero = '$heroid' 
	AND dp.item5 != '\0\0\0\0' 
    AND dp.item5 != '' 
	AND dp.item5 != '$mostItem1' AND dp.item5 != '$mostItem11'
	AND dp.item5 != '$mostItem2' AND dp.item5 != '$mostItem22'
	AND dp.item5 != '$mostItem3' AND dp.item5 != '$mostItem33'
	AND dp.item5 != '$mostItem4' AND dp.item5 != '$mostItem44'
	GROUP BY item5 having count(*) > 1 
	ORDER BY count(*) DESC LIMIT 2";
	return $sql;
	}
	function getHeroItem6($heroid,$mostItem1,$mostItem11,$mostItem2,$mostItem22,$mostItem3,$mostItem33,$mostItem4,$mostItem44,$mostItem5,$mostItem55) {
	$sql = "SELECT count(*) as total, dp.item6, i.icon , i.name , i.itemid
	FROM ".OSDB_DP." as dp
	LEFT JOIN ".OSDB_ITEMS." as i ON i.itemid = dp.item6
	WHERE hero = '$heroid' 
	AND dp.item6 != '\0\0\0\0' 
    AND dp.item6 != '' 
	AND dp.item6 != '$mostItem1' AND dp.item6 != '$mostItem11'
	AND dp.item6 != '$mostItem2' AND dp.item6 != '$mostItem22'
	AND dp.item6 != '$mostItem3' AND dp.item6 != '$mostItem33'
	AND dp.item6 != '$mostItem4' AND dp.item6 != '$mostItem44'
	AND dp.item6 != '$mostItem5' AND dp.item6 != '$mostItem55'
	GROUP BY item6 having count(*) > 1 
	ORDER BY count(*) DESC LIMIT 2";
	return $sql;
	}
	
	
	function getHeroHistory($minPlayedRatio,$heroid,$order,$sortdb,$offset, $rowsperpage,$LEAVER) {
	$text = "
	SELECT CASE WHEN (kills = 0) THEN 0 WHEN (deaths = 0) then 1000 ELSE (kills*1.0/deaths*1.0) end as kdratio, 
	dp.gameid as gameid, 
	g.gamename, 
	dg.winner,
	kills, 
	deaths,
	assists, 
	creepkills, 
	neutralkills, 
	creepdenies, 
	towerkills, 
	raxkills, 
	courierkills, 
	b.name as name, 
	b.ip as ip,
	f.name as banname, 
	CASE when(gamestate = '17') then 'PRIV' else 'PUB' end as type, 
	CASE when ((winner=1 AND newcolour < 6) 
	or (winner=2 and newcolour > 5)) 
	AND b.`left`/g.duration >= $minPlayedRatio  then 'WON' when ((winner=2 AND newcolour < 6) 
	or (winner=1 and newcolour > 5)) 
	AND b.`left`/g.duration >= $minPlayedRatio  then 'LOST' when  winner=0 then 'DRAW' else '$LEAVER' end as result 
	FROM ".OSDB_DP." AS dp 
	LEFT JOIN ".OSDB_GP." AS b ON b.gameid = dp.gameid 
	AND dp.colour = b.colour 
	LEFT JOIN ".OSDB_DG." AS dg ON dg.gameid = dp.gameid
	LEFT JOIN ".OSDB_GAMES." AS g ON g.id = dp.gameid 
	LEFT JOIN ".OSDB_HEROES." as e ON dp.hero = heroid 
	LEFT JOIN ".OSDB_BANS." as f ON b.name = f.name 
	WHERE original = '$heroid' 
	ORDER BY $order $sortdb 
	LIMIT $offset, $rowsperpage";
 
	return $text;
	}
	
	function getUserGameHistory($LEAVER,$username,$order,$sortdb,$offset, $rowsperpage,$minPlayedRatio) {
	$text = "SELECT 
	winner, 
	dp.gameid as id, 
	newcolour, 
	datetime, 
	gamename, 
	original, 
	description, 
	kills, 
	deaths, 
	assists, 
	creepkills, 
	creepdenies, 
	neutralkills, 
	name, 
    CASE when(gamestate = '17') then 'PRIV' else 'PUB' end as type,
    CASE WHEN (kills = 0) THEN 0 WHEN (deaths = 0) then 1000 ELSE (kills*1.0/deaths) end as kdratio,
    CASE when ((winner=1 and newcolour < 6) 
	or (winner=2 and newcolour > 5)) 
	AND gp.`left`/g.duration >= $minPlayedRatio  then 'WON' when ((winner=2 and newcolour < 6) 
	or (winner=1 and newcolour > 5)) 
	AND gp.`left`/g.duration >= $minPlayedRatio  then 'LOST' when  winner=0 then 'DRAW' else '$LEAVER' end as outcome 
	FROM ".OSDB_DP." AS dp 
	LEFT JOIN ".OSDB_GP." AS gp ON gp.gameid = dp.gameid and dp.colour = gp.colour 
	LEFT JOIN ".OSDB_DG." AS dg ON dg.gameid = dp.gameid 
	LEFT JOIN ".OSDB_GAMES." AS g ON g.id = dp.gameid 
	LEFT JOIN ".OSDB_HEROES." as e ON dp.hero = heroid 
	WHERE LOWER(name) = LOWER('$username') and original <> 'NULL' 
	ORDER BY $order $sortdb, g.id $sortdb 
	LIMIT $offset, $rowsperpage";
 
	return $text;
	}
	
	
	function longGameWon($username, $limit = 1) {
	$sql = "SELECT (dg.min * 60 + dg.sec) AS longgamewon, 
	dg.gameid,
	g.gamename, 
	g.duration, 
	dp.kills, 
	dp.deaths, 
	dp.creepkills, 
    dp.creepdenies,	
	dp.assists, 
	dp.neutralkills,
	dp.newcolour 
			FROM ".OSDB_GP." as gp
			LEFT JOIN ".OSDB_GAMES." as g ON g.id = gp.gameid 
			LEFT JOIN ".OSDB_DP." as dp ON dp.gameid = g.id AND dp.colour = gp.colour 
			LEFT JOIN ".OSDB_DG." as dg ON g.id = dg.gameid 
			WHERE LOWER(name) = LOWER('$username')
			AND (
					(
						winner = 1 
						AND dp.newcolour >= 1
						AND dp.newcolour <= 5
					) 
					OR
					(
						winner = 2 
						AND dp.newcolour >= 7 
						AND dp.newcolour <= 11
					)
				)
			GROUP BY dg.gameid
			ORDER BY longgamewon DESC
			LIMIT $limit";
			return $sql;
	}
	
	function fastGameWon($username, $limit = 1) {
	$sql = "SELECT dg.min * 60 + dg.sec AS fastgamewon, 
	dg.gameid, 
	g.gamename, 
	g.duration, 
	dp.kills, 
	dp.deaths, 
	dp.creepkills, 
    dp.creepdenies,	
	dp.assists, 
	dp.neutralkills,
	dp.newcolour 
			FROM ".OSDB_GP." as gp
			LEFT JOIN ".OSDB_GAMES." as g ON g.id = gp.gameid 
			LEFT JOIN ".OSDB_DP." as dp ON dp.gameid = g.id AND dp.colour = gp.colour 
			LEFT JOIN ".OSDB_DG." as dg ON g.id = dg.gameid 
			WHERE LOWER(name) = LOWER('$username')
			AND (
					(
						winner = 1 
						AND dp.newcolour >= 1
						AND dp.newcolour <= 5
					) 
					OR
					(
						winner = 2 
						AND dp.newcolour >= 7 
						AND dp.newcolour <= 11
					)
				)
			GROUP BY dg.gameid
			ORDER BY fastgamewon ASC
			LIMIT $limit";
			return $sql;
	}
	
	function GetGameDurations($username) {
	$sql = "SELECT 
	MIN(datetime), 
	MIN(loadingtime), 
	MAX(loadingtime), 
	AVG(loadingtime), 
	MIN(`left`), 
	MAX(`left`), 
	AVG(`left`), 
	SUM(`left`) 
	FROM ".OSDB_GP." as gp
	LEFT JOIN ".OSDB_GAMES." as g ON g.id=gp.gameid 
	LEFT JOIN ".OSDB_DP." as dp ON dp.gameid=g.id 
	AND dp.colour=gp.colour 
	LEFT JOIN ".OSDB_DG." as dg ON g.id=dg.gameid 
	WHERE LOWER(name)=LOWER('".$username."') LIMIT 1";
	
	return $sql;
	}
	
function GetMostPlayedHero($username, $limit = 1) {
   $username = strtolower($username);
   $sql = "SELECT SUM(`left`) AS timeplayed, original, description, 
	COUNT(*) AS played 
	FROM ".OSDB_GP." as gp
	LEFT JOIN ".OSDB_GAMES." as g ON g.id=gp.gameid 
	LEFT JOIN ".OSDB_DP." as dp ON dp.gameid=g.id 
	AND dp.colour=gp.colour  
	LEFT JOIN ".OSDB_DG." as dg ON g.id=dg.gameid 
    JOIN ".OSDB_HEROES." on hero = heroid 
	WHERE LOWER(name)=LOWER('".$username."')
	GROUP BY original 
	ORDER BY played DESC LIMIT ".$limit."";
	return $sql;
}

function GetMostKillsHero($username, $limit = 1) {
   $username = strtolower($username);
   $sql = "SELECT 
	original, description, max(kills) as maxkills, g.id as gameid
	FROM ".OSDB_DP." as dp
	LEFT JOIN gameplayers AS gp ON gp.gameid = dp.gameid AND dp.colour = gp.colour 
	LEFT JOIN heroes on hero = heroid 
	LEFT JOIN ".OSDB_GAMES." as g ON g.id = dp.gameid
	WHERE LOWER(name)= LOWER('".$username."') 
	GROUP BY kills 
	ORDER BY maxkills DESC LIMIT ".$limit."";
	return $sql;
}

function GetMostDeathsHero($username, $limit = 1) {
   $username = strtolower($username);
   $sql = "SELECT original, description, max(deaths) as maxdeaths, g.id as gameid
	FROM ".OSDB_DP." AS a 
	LEFT JOIN gameplayers AS b ON b.gameid = a.gameid and a.colour = b.colour 
	LEFT JOIN heroes on hero = heroid 
	LEFT JOIN ".OSDB_GAMES." as g ON g.id = a.gameid
	WHERE LOWER(name) = LOWER('".$username."') 
	GROUP BY deaths 
	ORDER BY maxdeaths DESC 
	LIMIT ".$limit."";
	return $sql;
}

function GetMostAssistsHero($username, $limit = 1) {
   $username = strtolower($username);
   $sql = "SELECT original, description, max(assists) as maxassists, g.id as gameid
	FROM ".OSDB_DP." AS a 
	LEFT JOIN gameplayers AS b ON b.gameid = a.gameid and a.colour = b.colour 
	LEFT JOIN heroes on hero = heroid 
	LEFT JOIN ".OSDB_GAMES." as g ON g.id = a.gameid
	WHERE LOWER(name) = LOWER('".$username."') 
	GROUP BY assists 
	ORDER BY maxassists DESC 
	LIMIT ".$limit."";
	return $sql;
}

function GetMostWinsHero($username, $limit = 1) {
   $username = strtolower($username);
   $sql = "SELECT original, description, COUNT(*) as wins, g.id as gameid
	FROM ".OSDB_GP." as gp
	LEFT JOIN ".OSDB_GAMES." as g ON g.id=gp.gameid 
	LEFT JOIN ".OSDB_DP." as dp ON dp.gameid=g.id 
	AND dp.colour=gp.colour 
	LEFT JOIN ".OSDB_DG." as dg ON g.id=dg.gameid 
	LEFT JOIN ".OSDB_HEROES." on hero = heroid 
	WHERE LOWER(name) = LOWER('".$username."') 
	AND((winner=1 
	AND dp.newcolour>=1 
	AND dp.newcolour<=5) 
	OR (winner=2 
	AND dp.newcolour>=7 
	AND dp.newcolour<=11)) 
	GROUP BY original ORDER BY wins DESC LIMIT ".$limit."";
	return $sql;
}

function GetMostLossesHero($username, $limit = 1) {
   $username = strtolower($username);
   $sql = "SELECT original, description, COUNT(*) as losses 
	FROM ".OSDB_GP." as gp
	LEFT JOIN ".OSDB_GAMES." as g ON g.id=gp.gameid 
	LEFT JOIN ".OSDB_DP." as dp ON dp.gameid=g.id 
	AND dp.colour=gp.colour 
	LEFT JOIN ".OSDB_DG." as dg ON g.id=dg.gameid 
	LEFT JOIN ".OSDB_HEROES." on hero = heroid 
	WHERE LOWER(name) = LOWER('".$username."') 
	AND((winner=2 AND dp.newcolour>=1 AND dp.newcolour<=5) OR (winner=1 AND dp.newcolour>=7 AND dp.newcolour<=11)) 
	GROUP BY original ORDER BY losses DESC LIMIT ".$limit."";
	return $sql;
}
	
///////////////////////

function ShowToolTip($text, $img = "", $width = "", $imgwidth = "", $imgheight = "") {
  ?> onMouseout="hidetooltip()" onMouseover="tooltip('<?=os_strip_quotes($text)?>', '<?=$img?>', <?=$width?>, <?=$imgwidth?>, <?=$imgheight?>)" 
  <?php
}

function convEnt($text){
return str_replace(
array('<br>', '&#039;', '&quot;', '&amp;', '&#36;', '&lt;', '&gt;'), 
array("\r\n", "'", '"', '&amp;', '$', '<', '>'), $text);
}

function convEnt2($text){
return strip_tags(str_replace(
array("'", '"', "<", ">",'$'), 
array('&#039;', '&quot;','&lt;', '&gt;','&#36;'), $text));
}


function os_strip_quotes($text) {
return str_replace(array("'", '"'), array("", ''), $text);
}

///////////////////////

   function my_nl2br($str, $rep = "\r\n", $max = 2) {
$arr = explode("\r\n", $str);
$str = '';
$nls = 0;
    foreach($arr as $line) {
    $str .= $line;
    if (empty($line)) {
    $nls++;
    } else {
    $nls = 0;
           }
      if ($nls < $max) {
      $str .= $rep;
                       }
      }
return substr($str, 0, strlen($str) - strlen($rep));
}

function br2nl($string)
{
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}

function OS_StrToUTF8( $text ) {
   $text = htmlspecialchars( html_entity_decode( $text ), ENT_QUOTES, 'UTF-8'); 
   return $text;
}

function PrepareTextDB($text) {

  $text = ( trim($text) );
  while ( strstr($text, "\n\n") ) $text = str_replace("\n\n", "\n", $text);
  $text = str_replace("\n\r\n\r", "\n\r", $text);
  while ( strstr($text, "\n\r\n\r") ) $text = str_replace("\n\r\n\r", "\n\r", $text);
  $text = str_replace("\n", "<br />", $text);
  $text = preg_replace('/\v+|\\\[rn]/','<br />', $text);
  $text = nl2br($text)."" ;
  while ( strstr($text, "<br /><br />") ) $text = str_replace("<br /><br />", "<br />", $text);
  $text = str_replace("<br /><br />", "<br />", $text);
  
  $text = stripslashes($text);
  
  $text = EscapeStr( ($text) );
  
  //if (get_magic_quotes_gpc())
  //$text = stripslashes($text);
	
  return $text;
}

function BBCode ($text) {
$search = array(
    '@\[(?i)b\](.*?)\[/(?i)b\]@si',
    '@\[(?i)i\](.*?)\[/(?i)i\]@si',
    '@\[(?i)u\](.*?)\[/(?i)u\]@si',
	'#\[s\](.*?)\[/s\]#is',
	'/\[ul\]/is',
	'/\[\/ul\]/is',
	'/\[li\]/is',
	'/\[\/li\]/is',
    '#\[img\](.*?)\[/img\]#i',
    '@\[(?i)url=(.*?)\](.*?)\[/(?i)url\]@si',
	'/\[url\]([^\"]*?)\[\/url\]/si',
	'/\[font(#[A-F0-9]{6})\](.+?)\[\/font\]/is',
	'/\[font=([^\]]*?)\]([\s\S]*?)\[\/font\]/is',
	'/\[color(#[A-F0-9]{6})\](.+?)\[\/color\]/is',
	'/\[color=([^\]]*?)\]([\s\S]*?)\[\/color\]/is',
	'~\[quote\]~is',
	'~\[/quote\]~is',
	'~\[quote=(.+?)\]~is',
	'/\[justify\][\r\n]*(.+?)\[\/justify\][\r\n]*/si',
	'/\[youtube=http:\/(\/www\.|\/[a-z]+\.|\/)youtube\.com\/watch\?v=([a-zA-Z0-9-_]+)(.*)\]/si',
	'/\[youtube]http:\/(\/www\.|\/[a-z]+\.|\/)youtube\.com\/watch\?v=([a-zA-Z0-9-_]+)(.*)\[\/youtube\]/si',
    '@\[(?i)code\](.*?)\[/(?i)code\]@si',
	'/\[code\](.*?)\[\/code\]/is',
	'/\[left\](.*?)\[\/left\]/is',
	'/\[right\](.*?)\[\/right\]/is',
	'/\[center\](.*?)\[\/center\]/is',
	'#\[size=([1-9]|1[0-9]|24)\](.*?)\[/size\]#is',
	'/\[hl\][\r\n]*(.+?)\[\/hl\][\r\n]*/is',
	'/\[php\](.*?)\[\/php\]/is',
	'/\[spoiler\][\r\n]*(.+?)\[\/spoiler\][\r\n]*/si',
);
$replace = array(
    '<b>\\1</b>',
    '<i>\\1</i>',
    '<u>\\1</u>',
	'<span style="text-decoration: line-through;">$1</span>',
	'<ul>',
	'</ul>',
	'<li>',
	'</li>',
    '<img src="\\1"/>',
    '<a href="\\1" target="_blank">\\2</a>',
	'<a href="\\1" target="_blank">\\1</a>',
	'<span style="color:\\1">\\2</span>',
	'<span style=\"color: $1\">$2</span>',
	'<span style="color:\\1">\\2</span>',
	'<span style="color: $1">$2</span>',
	
	'<table style="width:90%" border=0><tr><td class="singlequoting">',
	'</td></tr></table>',
	
	'<table style="width:90%"><tr><td class="quoting">\\1</td></tr><tr><td class="quote">\\2',
	
	'<div align="justify">\\1</div>',
	'<object width=\"640\" height=\"385\"><param name=\"movie\" value=\"http://www.youtube.com/v/\\2\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"http://www.youtube.com/v/\\2\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"640\" height=\"385\"></embed></object>',
	'<object width=\"640\" height=\"385\"><param name=\"movie\" value=\"http://www.youtube.com/v/\\2\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"http://www.youtube.com/v/\\2\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"640\" height=\"385\"></embed></object>',
    '<pre>\\1</pre>',	
	'<pre>$1</pre>',
	'<div style="text-align: left;">$1</div>',
	'<div style="text-align: right;">$1</div>',
	'<div style="text-align: center;">$1</div>',
	'<span style="font-size: $1px;">$2</span>',
	'<span class="hl">\\1</span>',
	'<pre class="brush: php;">$1</pre>',
	'<div class="spoilerdiv"><input class="spoiler" type="button" onclick="showSpoiler(this);" value="Show/Hide" /><div class="inner" style="display:none;">$1</div></div>');
return preg_replace($search , $replace, $text);
}

function BBDecode ($text) {
$search = array(
    '/<a href=\"([^<> \n\r\[\]]+?)\" target=\"(_new|_blank)\">(.+?)<\/a>/i',
	'/<span style="color: (.+?)">(.+?)<\/span>/is',
    '~<table style="width:90%" border=0><tr><td class="singlequoting">(.+?)</td></tr></table>~is',
    '/<a\s[^<>]*?href=\"?([^<>]*?)\"?(\s[^<>]*)?>([^<>]*?)<\/a>/si',
    '/<b>(.+?)<\/b>/is',
    '/<u>(.+?)<\/u>/is',
	'/<i>(.+?)<\/i>/is',
	'/<span style="font-size: (.+?)px;\">(.+?)<\/span>/is',
	'/<span style="text-decoration: line-through;\">(.+?)<\/span>/is',
	
	'~<table style="width:90%"><tr><td class="quoting">(.+?)</td></tr><tr><td class="quote">(.+?)</td></tr></table>~is',
	
	'~<table style="width:90%"><tr><td class="quoting">(.+?)</td></tr><tr><td class="quote">~is',
	
	'~</td></tr></table>~is',
	
	'/<div style="text-align: center;">(.+?)<\/div>/is',
	'/<div style="text-align: left;">(.+?)<\/div>/is',
	'/<div style="text-align: right;">(.+?)<\/div>/is',
	'/<div align="justify">(.+?)<\/div>/is',
	'/<img src=\"([^<> \n\r\[\]&]+?)\" alt=\"(.+?)\" (title=\"(.+?)\" )?\/>/si',
	'/<img\s[^<>]*?src=\"?([^<>]*?)\"?(\s[^<>]*)?\/?>/si',
	'/<object width=\"[0-9]+\" height=\"[0-9]+\"><param name=\"movie\" value=\"http:\/\/www\.youtube\.com\/v\/([a-zA-Z0-9-_]+)\"><\/param><param name=\"wmode\" value=\"transparent\"><\/param><embed src=\"http:\/\/www\.youtube\.com\/v\/([a-zA-Z0-9-_]+)\" type=\"application\/x-shockwave-flash\" wmode=\"transparent\" width=\"[0-9]+\" height=\"[0-9]+\"><\/embed><\/object>/si',
	'/<span class="hl">(.+?)<\/span>/is',
	'/<pre class="brush: php;">(.+?)<\/pre>/is',
	'/<div class="spoilerdiv"><input class="spoiler" type="button" onclick="showSpoiler\(this\);" value="Show\/Hide" \/><div class="inner" style="display:none;">(.+?)<\/div><\/div>/is'
);
$replace = array(
    '[url=\\1]\\3[/url]',
    '[color=\\1]\\2[/color]',
    '[quote]\\1[/quote]',
    '[url]$3[/url]',
    '[b]\\1[/b]',
	'[u]\\1[/u]',
	'[i]\\1[/i]',
	'[size=\\1]\\2[/size]',
	'[s]\\1[/s]',
	'[quote=\\1]\\2[/quote]',
	'[quote=\\1]',
	'[/quote]',
	'[center]\\1[/center]',
	'[left]\\1[/left]',
	'[right]\\1[/right]',
	'[justify]\\1[/justify]',
	'[img=\\1]\\2[/img]',
	'[img]$1[/img]',
	'[youtube]http://www.youtube.com/watch?v=\\1[/youtube]',
	'[hl]\\1[/hl]',
	'[php]\\1[/php]',
	'[spoiler]\\1[/spoiler]'
);
return preg_replace($search , $replace, $text);
}

function is_logged() {
   if ( 
     isset( $_SESSION["username"]) AND  
     isset( $_SESSION["email"])    AND  
     isset( $_SESSION["level"])    AND  
     isset( $_SESSION["logged"])   AND  
     isset( $_SESSION["user_id"])
   ) 
   return true;
   else return false;
}

function os_is_logged() {
   if ( 
     isset( $_SESSION["username"]) AND  
     isset( $_SESSION["email"])    AND  
     isset( $_SESSION["level"])    AND  
     isset( $_SESSION["logged"])   AND  
     isset( $_SESSION["user_id"])
   ) 
   return true;
   else return false;
}

function os_logout() {
   if ( isset($_SESSION["user_id"]) )     unset($_SESSION["user_id"]);
   if ( isset($_SESSION["username"]) )    unset($_SESSION["username"]);
   if ( isset($_SESSION["email"]) )       unset($_SESSION["email"]);
   if ( isset($_SESSION["level"]) )       unset($_SESSION["level"]);
   if ( isset($_SESSION["can_comment"]) ) unset($_SESSION["can_comment"]);
   if ( isset($_SESSION["logged"]) )      unset($_SESSION["logged"]);
   session_destroy();
}

  function convHTML($ic1,$ic2,$ic3,$ic4,$ic5,$ic6,$HTML,$hero,$hero2,$url){
  
              $HTML = str_replace("$ic1","",$HTML);
			  $HTML = str_replace("$ic2","",$HTML);
			  $HTML = str_replace("$ic3","",$HTML);
			  $HTML = str_replace("$ic4","",$HTML);
			  $HTML = str_replace("$ic5","",$HTML);
			  $HTML = str_replace("$ic6","",$HTML);
			  $HTML = str_replace("'./img/items/","'$url/img/items/",$HTML);
			  $HTML = str_replace("$hero",
			  "<img title='$hero2' alt='' width='32' height='32' src='$url/img/heroes/$hero2.gif' />",$HTML);
			  //$HTML = BBDecode($HTML);
              //$HTML = strip_tags($HTML);
			  return $HTML;
  
  } 
  //Get links from playdota.com (eg. http://www.playdota.com/heroes/HERO_NAME )
  //Function autogenerated by script (this is still experimental feature)
  function get_HeroByID($hid) {
  $return = "";
     if ($hid == 'H06S') $return = 'admiral'; 
     if ($hid == 'N01I') $return = 'alchemist'; 
     if ($hid == 'N0HP') $return = 'ancient-apparition'; 
     if ($hid == 'EDEM') $return = 'anti-mage'; 
     if ($hid == 'OPGH') $return = 'axe'; 
     if ($hid == 'OSHD') $return = 'bane-elemental'; 
     if ($hid == 'O016') $return = 'batrider'; 
     if ($hid == 'H00D') $return = 'beastmaster'; 
     if ($hid == 'HVSH') $return = 'bloodseeker'; 
     if ($hid == 'E004') $return = 'bone-fletcher'; 
     if ($hid == 'NAKA') $return = 'bounty-hunter'; 
     if ($hid == 'H008') $return = 'bristleback'; 
     if ($hid == 'U006') $return = 'broodmother'; 
     if ($hid == 'U00F') $return = 'butcher'; 
     if ($hid == 'H000') $return = 'centaur-warchief'; 
     if ($hid == 'U00A') $return = 'chaos-knight'; 
     if ($hid == 'H00T') $return = 'clockwerk-goblin'; 
     if ($hid == 'HJAI') $return = 'crystal-maiden'; 
     if ($hid == 'H00N') $return = 'dark-seer'; 
     if ($hid == 'UC76') $return = 'death-prophet'; 
     if ($hid == 'UC18') $return = 'demon-witch'; 
     if ($hid == 'UC42') $return = 'doom-bringer'; 
     if ($hid == 'HLGR') $return = 'dragon-knight'; 
     if ($hid == 'NBRN') $return = 'drow-ranger'; 
     if ($hid == 'USYL') $return = 'dwarven-sniper'; 
     if ($hid == 'OTCH') $return = 'earthshaker'; 
     if ($hid == 'EMOO') $return = 'enchantress'; 
     if ($hid == 'UKTL') $return = 'enigma'; 
     if ($hid == 'EC45') $return = 'faceless-void'; 
     if ($hid == 'N00B') $return = 'faerie-dragon'; 
     if ($hid == 'E02J') $return = 'disruptor'; 
     if ($hid == 'H00I') $return = 'geomancer'; 
     if ($hid == 'H00K') $return = 'goblin-techies'; 
     if ($hid == 'H00V') $return = 'gorgon'; 
     if ($hid == 'O01F') $return = 'guardian-wisp'; 
     if ($hid == 'E02N') $return = 'gyrocopter'; 
     if ($hid == 'H00A') $return = 'holy-knight'; 
     if ($hid == 'H00U') $return = 'invoker'; 
     if ($hid == 'NBBC') $return = 'juggernaut'; 
     if ($hid == 'HBLM') $return = 'keeper-of-the-light'; 
     if ($hid == 'ULIC') $return = 'lich'; 
     if ($hid == 'U00C') $return = 'lifestealer'; 
     if ($hid == 'E002') $return = 'lightning-revenant'; 
     if ($hid == 'N01O') $return = 'lone-druid'; 
     if ($hid == 'UDEA') $return = 'lord-of-avernus'; 
     if ($hid == 'HMBR') $return = 'lord-of-olympus'; 
     if ($hid == 'U008') $return = 'lycanthrope'; 
     if ($hid == 'UC11') $return = 'magnataur'; 
     if ($hid == 'E005') $return = 'moon-rider'; 
     if ($hid == 'O00P') $return = 'morphling'; 
     if ($hid == 'H071') $return = 'murloc-nightcrawler'; 
     if ($hid == 'HC49') $return = 'naga-siren'; 
     if ($hid == 'UC60') $return = 'necrolic'; 
     if ($hid == 'U00E') $return = 'necrolyte'; 
     if ($hid == 'U000') $return = 'nerubian-assassin'; 
     if ($hid == 'UBAL') $return = 'nerubian-weaver'; 
     if ($hid == 'EC77') $return = 'netherdrake'; 
     if ($hid == 'UDRE') $return = 'night-stalker'; 
     if ($hid == 'H00H') $return = 'oblivion'; 
     if ($hid == 'U00P') $return = 'obsidian-destroyer'; 
     if ($hid == 'HMKG') $return = 'ogre-magi'; 
     if ($hid == 'HARF') $return = 'omniknight'; 
     if ($hid == 'NPBM') $return = 'pandaren-brewmaster'; 
     if ($hid == 'EWAR') $return = 'phantom-assassin'; 
     if ($hid == 'OGRH') $return = 'phantom-lancer'; 
     if ($hid == 'E02F') $return = 'phoenix'; 
     if ($hid == 'N00R') $return = 'pit-lord'; 
     if ($hid == 'N01V') $return = 'priestess-of-the-moon'; 
     if ($hid == 'EMNS') $return = 'prophet'; 
     if ($hid == 'UC01') $return = 'queen-of-pain'; 
     if ($hid == 'H001') $return = 'rogue-knight'; 
     if ($hid == 'H00Q') $return = 'sacred-warrior'; 
     if ($hid == 'U00K') $return = 'sand-king'; 
     if ($hid == 'E02H') $return = 'shadow-demon'; 
     if ($hid == 'NFIR') $return = 'shadow-fiend'; 
     if ($hid == 'N01W') $return = 'shadow-priest'; 
     if ($hid == 'ORKN') $return = 'shadow-shaman'; 
     if ($hid == 'N01A') $return = 'silencer'; 
     if ($hid == 'NC00') $return = 'skeleton-king'; 
     if ($hid == 'H004') $return = 'slayer'; 
     if ($hid == 'UC91') $return = 'slithereen-guard'; 
     if ($hid == 'EEVI') $return = 'soul-keeper'; 
     if ($hid == 'E01B') $return = 'spectre'; 
     if ($hid == 'O00J') $return = 'spiritbreaker'; 
     if ($hid == 'HC92') $return = 'stealth-assassin'; 
     if ($hid == 'UCRL') $return = 'stone-giant'; 
     if ($hid == 'H00S') $return = 'storm-spirit'; 
     if ($hid == 'O015') $return = 'tauren-chieftain'; 
     if ($hid == 'E01Y') $return = 'templar-assassin'; 
     if ($hid == 'OFAR') $return = 'tidehunter'; 
     if ($hid == 'NTIN') $return = 'tinker'; 
     if ($hid == 'EKEE') $return = 'tormented-soul'; 
     if ($hid == 'HAMG') $return = 'treant-protector'; 
     if ($hid == 'N016') $return = 'troll-warlord'; 
     if ($hid == 'E02I') $return = 'tuskarr'; 
     if ($hid == 'E00P') $return = 'twin-head-dragon'; 
     if ($hid == 'H00R') $return = 'undying'; 
     if ($hid == 'HUTH') $return = 'ursa-warrior'; 
     if ($hid == 'HVWD') $return = 'vengeful-spirit'; 
     if ($hid == 'EC57') $return = 'venomancer'; 
     if ($hid == 'E01C') $return = 'warlock'; 
     if ($hid == 'N0EG') $return = 'windrunner'; 
     if ($hid == 'E01A') $return = 'witch-doctor';
	 if ($hid == 'E02X') $return = 'grand-magus';
 
  return $return;
  }
  
  function limit_words($string, $word_limit, $dots = 1)
{
    $string = (strip_tags($string));
	$string = str_replace("\r\n","",$string);
	$string = str_replace("&nbsp;","",$string);
	$string = str_replace("\n","",$string);
	//$string = preg_replace('/\<script>(.*?)</script>/si', '', $string);
	//while( strstr($string, "\t") ) $string = str_replace("\t","",$string); 
    $words = explode(" ",$string);
	if ($dots==1) $add = ""; else $add = "";
    return implode(" ",array_splice($words,0,$word_limit)).$add;
}
  
  function generate_password($pass, $salt = "0#'open73^743_stats_923^$&_") {
  $password = substr(md5($salt),0,3).sha1($pass.$salt).substr(md5($pass),0,3).substr(sha1($salt),0,3);
  return $password;
  }
  
  function generate_hash($length=22, $alphnum = 0 ) {
 $alphanum = '0123456789qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm0123456789';
 if ($alphnum==1) $alphanum.="!@#$^()_|";
 $rand = strtolower(substr(str_shuffle($alphanum), 0, $length));
 return $rand;
 }

 function write_value_of($var,$oldval,$newval, $file)
{
 $contents = file_get_contents($file);
 $regex = '~\\'.$var.'\s+=\s+\''.$oldval.'\';~is';
 $contents = preg_replace($regex, "$var = '$newval';", $contents);
 file_put_contents($file, $contents);
}
  if ($OS_INSTALLED == 0 AND !file_exists("install/install.php") ) { os_trigger_error("Missing install folder."); }
  if ($OS_INSTALLED == 0) { require_once("install/install.php"); die; } else {
   if (file_exists("install") )             os_trigger_error("Please delete <b>install/</b> folder");
   if (file_exists("install/install.php") ) os_trigger_error("Please delete or rename <b>install.php</b>");
   if (file_exists("sql_data.sql") ) os_trigger_error("Please delete or rename <b>sql_data.sql</b>");
   if (file_exists("sql_heroes_items.sql") ) os_trigger_error("Please delete or rename <b>sql_heroes_items.sql</b>");
}

	function get_value_of($name, $file = "../config.php")
    {
    $lines = file($file);
	 $val = array();
     foreach (array_values($lines) AS $line)
     {
	   if (strstr($line,"="))
	   {
       list($key, $val) = explode('=', trim($line) );
       if (trim($key) == $name)
          {$val = str_replace(";","",$val); $val = str_replace("'","",$val); 
		  $val = str_replace('"',"",$val);  return $val;}
       }
     }
     return false;
  }

function removeDoubleSpaces($text) {
   while ( strstr($text, "\t") ) $text = str_replace("\t", " ", $text);
   while ( strstr($text, "  ") ) $text = str_replace("  ", " ", $text);
   $text = trim($text);
   return $text;
}

function AutoKeywords( $text ) {
   $text = str_replace(" ", ", ", $text);
   $text = strtolower( os_strip_quotes($text));
   return $text;
}

//Very basic link check
function is_valid_url( $url ) {
   if (function_exists('FILTER_VALIDATE_URL') ) {
     if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) return false;
     else return true;
   }
   else return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}

function LinkUserProfile( $username, $website, $class = "") {
  if (!empty($website) AND is_valid_url($website) ) {
  ?>
  <a <?=$class?> href="<?=$website?>"><?=$username?></a>
  <?php
  } else {
  echo $username;
  }
}

function DisplayGameFilter($year = "", $query = "games" ) {
?>
<form action="" method="get">
<input type="hidden" name="<?=$query?>" />
<select name="m">

 <option value=""></option>
<?php
  $ThisMonth = date('m', time() );
  for ( $counter = 1; $counter <= 12; $counter += 1) {
  $sel = "";
  if ( !isset($_GET["m"]) AND $ThisMonth == $counter )  $sel = 'selected="selected"'; else
  if ( isset($_GET["m"])  AND $_GET["m"] == $counter )  $sel = 'selected="selected"';  

   ?>
   <option <?=$sel?> value="<?=$counter?>"><?=getMonthName($counter)?></option>
   <?php
   }
?>
</select>

<select name="y">
  <?php
  $ThisYear =  date( "Y", time());
  $GoalYear = $year;
  for ( $counter = $ThisYear; $counter >= $GoalYear; $counter -= 1) {
  $sel = "";
  if ( isset($_GET["y"]) AND $_GET["y"] == $counter ) $sel = 'selected="selected"'; else 
  //if ( $year == $counter )  $sel = 'selected="selected"';
   ?>
   <option <?=$sel?> value="<?=$counter?>"><?=($counter)?></option>
   <?php
   }
?>
</select>
<input type="submit" value="Submit" class="menuButtons" />
</form>
<?php
}

function AutoLinkShort($text, $target = "" )
{
   $pattern  = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
   $callback = create_function('$matches', '
       $url       = array_shift($matches);
       $url_parts = parse_url($url);

       $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
       $text = preg_replace("/^www./", "", $text);

       $last = -(strlen(strrchr($text, "/"))) + 1;
       if ($last < 0) {
           $text = substr($text, 0, $last) . "&hellip;";
       }

       return sprintf(\'<a '.$target.' rel="nofollow" href="%s">%s</a>\', $url, $text);
   ');

   return preg_replace_callback($pattern, $callback, $text);
}

function AutoLinkFull($text, $target = "") {
  $pattern = "/(((http[s]?:\/\/)|(www\.))(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9.,_\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
  $text = preg_replace($pattern, " <a ".$target." href='$1'>$1</a>", $text);
  // fix URLs without protocols
  $text = preg_replace("/href='www/", "href='http://www", $text);
  return $text;
}

function RemoveLinks($text, $replaceTxt) {
  $pattern = "/(((http[s]?:\/\/)|(www\.))(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9.,_\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
  $text = preg_replace($pattern, "<i>".$replaceTxt."</i>", $text);
  // fix URLs without protocols
  //$text = preg_replace("/href='www/", "href='http://www", $text);
  return $text;
}

function GetHeroIcon() {
  if ( isset($_GET["h"]) AND file_exists("img/heroes/".strtoupper($_GET["h"]).".gif" ) ) {
   ?>
   <img class="imgvalign" src="img/heroes/<?=strtoupper($_GET["h"])?>.gif" alt="*" width="24" height="24" />
   <?php
  }
}

function os_get_footer() {
  include('themes/'.OS_THEMES_DIR.'/footer.php');
}

function os_commentForm( $style = 'style="width: 420px; height: 120px;"') {
  os_comment_form();
  
  if ( !defined('OS_ALWAYS_ENABLE_TEXTAREA') ) $disabled = 'disabled'; else $disabled = "";
  ?>
  <textarea <?php if ( !is_logged() ) { echo $disabled; } ?>  id="text_message" <?=$style?> name="post_comment"></textarea>
  <?php
  os_after_comment_form();
}

function os_canComment() {
   
   if ( is_logged() ) return true;
   
   if (!is_logged() ) {
	  if ( defined('OS_ALWAYS_ENABLE_TEXTAREA') ) return true;
	  else return false;
   }
   
}

function os_offset( $numrows, $result_per_page = 10 ) {

              $rowsperpage = $result_per_page;
              $totalpages = ceil($numrows / $rowsperpage);
              if (isset($_GET['page']) && is_numeric($_GET['page'])) {
                  $currentpage = (int)$_GET['page'];
              } else {
                  $currentpage = 1;
              }
              if ($currentpage > $totalpages) {
                  $currentpage = $totalpages;
              }
              if ($currentpage < 1) {
                  $currentpage = 1;
              }
              if ($totalpages <= 1) {
                  $totalpages = 1;
              }

              $offset = ($currentpage - 1) * $rowsperpage;
			  
	return $offset;
}

function os_pagination( $numrows, $result_per_page = 10, $MaxPaginationLinks = 5, $draw_pagination = 1, $prefix="", $SHOW_TOTALS = "" ) {

  global $lang;
  $end = "";
  
  if ( isset($_GET["action"]) ) $prefix.="?action=".safeEscape($_GET["action"]);
  
              $rowsperpage = $result_per_page;
              $totalpages = ceil($numrows / $rowsperpage);
              if (isset($_GET['page']) && is_numeric($_GET['page'])) {
                  $currentpage = (int)$_GET['page'];
              } else {
                  $currentpage = 1;
              }
              if ($currentpage > $totalpages) {
                  $currentpage = $totalpages;
              }
              if ($currentpage < 1) {
                  $currentpage = 1;
              }
              if ($totalpages <= 1) {
                  $totalpages = 1;
              }

              $offset = ($currentpage - 1) * $rowsperpage;
              if (isset($_GET['page']) AND is_numeric($_GET['page'])){
                          $current_page = safeEscape($_GET['page']);
                          }

                          if (!isset($current_page)) {
                              $current_page = 1;
                          }
              if (!isset($MaxPaginationLinks) ) $range = 5;
			  else  $range = $MaxPaginationLinks;
			  
              if ($range >= $totalpages) {
                  $range = $totalpages;
              }
			  
			  if ($current_page > $totalpages) {$current_page = $totalpages;}
			  
if (isset($draw_pagination) AND $draw_pagination == 1 AND $totalpages>=2) {
?>
	  <div class="pagination2"> 
	   <?php
              if ($currentpage > 1) {
                  ?><a class="button orange" href="<?=OS_HOME?><?=$prefix?>"><span>&laquo;</span></a><?php
                  $prevpage = $currentpage - 1;
                  ?><a class="button orange" href="<?=OS_HOME?><?=$prefix?>&amp;page=<?=$prevpage?><?=$end?>"><span><</span></a><?php
              }
              for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
                  if (($x > 0) && ($x <= $totalpages)) {
                      if ($x == $currentpage) {
                         ?>
					  <a class="button orange" href="javascript:;"><span class="active"><?=$x?></span></a><?php
                      } else {
                          ?>
					  <a class="button orange" href="<?=OS_HOME?><?=$prefix?>&amp;page=<?=$x?><?=$end?>"><span><?=$x?></span></a><?php
                      }
                  }
              }
              if ($currentpage != $totalpages) {
                  $nextpage = $currentpage + 1;
                 ?>
				 <a class="button orange" href="<?=OS_HOME?><?=$prefix?>&amp;page=<?=$nextpage?><?=$end?>"><span>></span></a>
				 
				 <a class="button orange" href="<?=OS_HOME?><?=$prefix?>&amp;page=<?=$totalpages?><?=$end?>"><span><?=$totalpages?></span></a><?php
              }
             ?>   
			<?php if (isset($SHOW_TOTALS) AND !empty($SHOW_TOTALS) ) { ?>
			 &nbsp;
			 <span class="totals"><?=$lang["page"]?> <b><?=$current_page?></b> <?=$lang["pageof"]?> <?=$totalpages?> 
			 (<?=$numrows?> <?=$lang["total"]?>)
			 </span>
			 <?php } ?>
			 </div>
			 <?php
    }
}

function os_trigger_error( $text = "" ) {
  //include('themes/'.OS_THEMES_DIR.'/header.php');
  ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta http-equiv="content-style-type" content="text/css" />
	<meta name="author" content="Ivan Antonijevic" />
	<meta name="rating" content="Safe For Kids" />
</head>

  <body>
     <div style="width:680px; height: 200px; border: 18px solid #ccc; text-align:center; margin: 0 auto; margin-top: 64px; padding-top: 16px; color: #5F5F5F; font-family: 'courier new', 'times new roman', monospace; font-size: 14px; border-radius: 10px;">
	   <?=$text?>
	 </div>
  </body>
</html>
<?php
die;
}

function PluginEnabled( $plugin ) {
  if ( !empty($plugin) ) {
  
    if ( isset($_GET["enable"]) AND $_GET["enable"] == $plugin ) return true;
	else 
	  return false;
		
  }
}

function PluginDisabled( $plugin ) {
  if ( !empty($plugin) ) {
  
    if ( isset($_GET["disable"]) AND $_GET["disable"] == $plugin ) return true;
	else 
	  return false;
		
  }
}

function OS_is_single() {
   if (isset($_GET["post_id"]) AND is_numeric($_GET["post_id"]) ) return true;
   else return false;
}

function OS_post_edit_link( $id ) {
   if ( OS_is_admin() AND $id>=1 ) {
   ?>
   <a href="<?=OS_HOME?>adm/?posts&amp;edit=<?=$id?>">edit entry</a> | 
   <?php
   }
}

function OS_top_page() {
   if ( isset($_GET["top"]) ) return true;
}

function OS_games_page() {
   if ( isset($_GET["games"]) ) return true;
}

function OS_heroes_page() {
   if ( isset($_GET["heroes"]) ) return true;
}

function OS_items_page() {
   if ( isset($_GET["items"]) ) return true;
}

function OS_bans_page() {
   if ( isset($_GET["bans"]) ) return true;
}

function OS_admins_page() {
   if ( isset($_GET["admins"]) ) return true;
}

function OS_profile_page() {
   if ( isset($_GET["profile"]) ) return true;
}

function OS_login_page() {
   if ( isset($_GET["login"]) ) return true;
}

function OS_single_user() {
   if ( isset($_GET["u"]) AND is_numeric($_GET["u"]) AND !isset($_GET["action"]) ) return true;
}

function OS_members_page() {
   if ( isset($_GET["members"]) ) return true;
}

function OS_single_game_page() {
   if ( isset($_GET["game"]) ) return true;
}



function OS_add_custom_field($field_id = "", $field_name = "" , $field_value = "") {

  global $db;
  
  $check = $db->query("SELECT * FROM ".OSDB_CUSTOM_FIELDS." 
	WHERE field_id = '".$field_id ."' AND field_name = '".$field_name."'");
  if ( $db->num_rows($check)<=0 ) {
  $result = $db->query("INSERT INTO ".OSDB_CUSTOM_FIELDS."(field_id, field_name, field_value) 
  VALUES('".$field_id ."', '".$field_name."', '".$field_value."' ) ");
  } else {
  $update = $db->query("UPDATE ".OSDB_CUSTOM_FIELDS." SET field_value = '".$field_value."' 
  WHERE field_id = '".$field_id ."' AND field_name = '".$field_name."' ");
  }

}


function OS_delete_custom_field($field_id = "", $field_name = "" , $field_value = "") {

  global $db;
  
  if ( !empty($field_value) ) $sql = " AND field_value = '".$field_value."'"; else $sql = "";
  
  if ( !empty($field_id) AND !empty($field_name) )
  $delete = $db->query("DELETE FROM ".OSDB_CUSTOM_FIELDS." 
  WHERE field_id = '".$field_id."' AND field_name = '".$field_name."' $sql");

}

//get data from custom field table
function OS_get_custom_field( $field_id = "", $field_name = "" , $field_value = "" ) {
   global $db;
   
   $result =  $db->query("SELECT * FROM ".OSDB_CUSTOM_FIELDS." WHERE field_id = '".$field_id."' AND field_name = '".$field_name."' ");
   $row = $db->fetch_array($result,'assoc');
   $value = $row["field_value"];
   $db->free($result);
   
   return $value;
}
//short function for $_GET["action"]
function OS_GetAction( $str = "" ) {
   
   if ( empty($str) AND isset( $_GET["action"] ) AND $_GET["action"] == "" ) return true;
     else 
     if ( !empty($str) AND isset($_GET["action"]) AND $_GET["action"] == $str ) return true;
   else
   return false;
   
}
//Get user id of logged user
function OS_GetUserID() {
   if ( isset($_SESSION["user_id"]) AND is_numeric($_SESSION["user_id"]) )
   return $_SESSION["user_id"];
}
//Get user email of logged user
function OS_GetUserEmail() {
   if ( isset($_SESSION["email"]) AND 
      preg_match("/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i", $_SESSION["email"]) 
      )
	  return $_SESSION["email"];
}

function OS_GetStats( $offset = 0, $row_per_page = 10, $order = 'score DESC', $filter = "" ) {
      
	  global $db;
	  $filter = safeEscape( $filter );
	  $order  = safeEscape( $order );
	  
	  if ( !empty($order) ) $sqlOrder = 'ORDER BY '.$order;
	  
	  if ( is_numeric($offset) AND is_numeric($row_per_page) )
	  $limit = 'LIMIT '.$offset.', '.$row_per_page.' ';
	  else $limit = '';
	  
	  $result = $db->query("SELECT s.id, s.player, s.score, s.games, s.wins, s.losses, s.draw, s.kills, s.deaths, s.assists, s.creeps, s.denies, s.neutrals, s.towers, s.rax, s.banned, s.ip 
	  FROM ".OSDB_STATS." as s 
	  WHERE s.id>=1 $filter
	  $sqlOrder
	  $limit");
	  
	  		  
	  $c=0;
      $Data = array();
	
	  while ($row = $db->fetch_array($result,'assoc')) {
	   
	    $Data[$c]["id"] = $row["id"]; 
	    $Data[$c]["player"] = $row["player"]; 
	    $Data[$c]["score"] = $row["score"]; 
		$Data[$c]["games"] = $row["games"]; 
		$Data[$c]["wins"] = $row["wins"]; 
		$Data[$c]["losses"] = $row["losses"]; 
		$Data[$c]["draw"] = $row["draw"]; 
		$Data[$c]["kills"] = $row["kills"]; 
		$Data[$c]["deaths"] = $row["deaths"]; 
		$Data[$c]["assists"] = $row["assists"]; 
		$Data[$c]["creeps"] = $row["creeps"]; 
		$Data[$c]["denies"] = $row["denies"]; 
		$Data[$c]["neutrals"] = $row["neutrals"]; 
		$Data[$c]["towers"] = $row["towers"]; 
		$Data[$c]["neutrals"] = $row["neutrals"]; 
		$Data[$c]["rax"] = $row["rax"]; 
		$Data[$c]["banned"] = $row["banned"]; 
		$Data[$c]["ip"] = $row["ip"]; 
		
	    $c++;
	  }
	  $db->free($result);	
    
	return ( $Data );
}

function OS_GetUserStats( $username = '' ) {
      
	  global $db;
	  
	  if ( !empty($username) ) {
	  
	  $result = $db->query("SELECT s.id, s.player, s.score, s.games, s.wins, s.losses, s.draw, s.kills, s.deaths, s.assists, s.creeps, s.denies, s.neutrals, s.towers, s.rax, s.banned, s.ip 
	  FROM ".OSDB_STATS." as s 
	  WHERE s.id>=1 AND LOWER(s.player) = LOWER('".safeEscape($username)."')
	  LIMIT 1");
	  
	  		  
	  $c=0;
      $Data = array();
	
	  $row = $db->fetch_array($result,'assoc');
	   
	    $Data[$c]["id"] = $row["id"]; 
	    $Data[$c]["player"] = $row["player"]; 
	    $Data[$c]["score"] = $row["score"]; 
		$Data[$c]["games"] = $row["games"]; 
		$Data[$c]["wins"] = $row["wins"]; 
		$Data[$c]["losses"] = $row["losses"]; 
		$Data[$c]["draw"] = $row["draw"]; 
		$Data[$c]["kills"] = $row["kills"]; 
		$Data[$c]["deaths"] = $row["deaths"]; 
		$Data[$c]["assists"] = $row["assists"]; 
		$Data[$c]["creeps"] = $row["creeps"]; 
		$Data[$c]["denies"] = $row["denies"]; 
		$Data[$c]["neutrals"] = $row["neutrals"]; 
		$Data[$c]["towers"] = $row["towers"]; 
		$Data[$c]["neutrals"] = $row["neutrals"]; 
		$Data[$c]["rax"] = $row["rax"]; 
		$Data[$c]["banned"] = $row["banned"]; 
		$Data[$c]["ip"] = $row["ip"]; 

	  $db->free($result);	
    
	return ( $Data );
	}
}

function OS_GetUserStatsByID( $userID = '' ) {
      
	  global $db;
	  
	  if ( is_numeric($userID) ) {
	  
	  $result = $db->query("SELECT s.id, s.player, s.score, s.games, s.wins, s.losses, s.draw, s.kills, s.deaths, s.assists, s.creeps, s.denies, s.neutrals, s.towers, s.rax, s.banned, s.ip 
	  FROM ".OSDB_STATS." as s 
	  WHERE s.id='".safeEscape( (int) $userID )."' 
	  LIMIT 1");
	  
	  		  
	  $c=0;
      $Data = array();
	
	  $row = $db->fetch_array($result,'assoc');
	   
	    $Data[$c]["id"] = $row["id"]; 
	    $Data[$c]["player"] = $row["player"]; 
	    $Data[$c]["score"] = $row["score"]; 
		$Data[$c]["games"] = $row["games"]; 
		$Data[$c]["wins"] = $row["wins"]; 
		$Data[$c]["losses"] = $row["losses"]; 
		$Data[$c]["draw"] = $row["draw"]; 
		$Data[$c]["kills"] = $row["kills"]; 
		$Data[$c]["deaths"] = $row["deaths"]; 
		$Data[$c]["assists"] = $row["assists"]; 
		$Data[$c]["creeps"] = $row["creeps"]; 
		$Data[$c]["denies"] = $row["denies"]; 
		$Data[$c]["neutrals"] = $row["neutrals"]; 
		$Data[$c]["towers"] = $row["towers"]; 
		$Data[$c]["neutrals"] = $row["neutrals"]; 
		$Data[$c]["rax"] = $row["rax"]; 
		$Data[$c]["banned"] = $row["banned"]; 
		$Data[$c]["ip"] = $row["ip"]; 

	  $db->free($result);	
    
	return ( $Data );
	}
}

function OS_Number( $num ) {
   $raw = filter_var( $num, FILTER_SANITIZE_NUMBER_INT);
   return $raw;
}

function OS_Post_Link( $post_id ) {
   $link = OS_HOME.'?post_id='.(int)$post_id;
   return $link;
}

function OS_show_errors( $errors ) {
  if ( isset($errors) AND !empty($errors) ) {
  ?>
  <div class="padTop padBottom padLeft"><?=$errors?></div>
  <?php
  }
}

function OS_MostPlayedHero( $username) {

   	$sql = "SELECT SUM(`left`) AS timeplayed, original, description, 
	COUNT(*) AS played 
	FROM gameplayers 
	LEFT JOIN games ON games.id=gameplayers.gameid 
	LEFT JOIN dotaplayers ON dotaplayers.gameid=games.id 
	AND dotaplayers.colour=gameplayers.colour  
	LEFT JOIN dotagames ON games.id=dotagames.gameid 
    JOIN heroes on hero = heroid 
	WHERE LOWER(name)=LOWER('".safeEscape($username)."')
	GROUP BY original 
	ORDER BY played DESC LIMIT 1";
	
	return $sql;
}

//Check if home page
function OS_is_home_page() {

 if ( !$_GET OR ( isset($_GET["post_id"])  OR (!isset($_GET["u"]) AND isset($_GET["page"])  ) ) 
   AND !isset($_GET["game"]) 
   AND !isset($_GET["games"]) 
   AND !isset($_GET["heroes"])  
   AND !isset($_GET["items"])
   AND !isset($_GET["warn"])
   AND !isset($_GET["safelist"])
   AND !isset($_GET["bans"])
   AND !isset($_GET["ban_appeals"])
   AND !isset($_GET["ban_reports"])
   AND !isset($_GET["admins"])
   AND !isset($_GET["about_us"])
   AND !isset($_GET["top"])
   AND !isset($_GET["members"])
   AND !isset($_GET["guides"])
   AND !isset($_GET["action"])
                            ) 
   {
    return true;
   } else return false;

}

function OS_GetGameState($PrivOrPub = '', $LangPub = 'PUB', $LangPriv = 'PRIV') {
    if ( $PrivOrPub == 17 ) $state = $LangPub;
	else  $state = $LangPriv;
	
	return $state;
}

function OS_RemoteFileExists($url) {

 $ch = curl_init($url);

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $retcode;
}

function OS_ShowPagination( $total, $results_show = 10,  $show = 1 ) {
  $numrows = $total;
  $result_per_page = $results_show;
  $draw_pagination = $show;
  
  include('inc/pagination.php');
}

function OS_is_banned_player( $player = "" ) {
  if ( !empty( $player) ) return true;
}

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}
?>